import useWindowWidth from '@/hooks/event/use-window-width';
import {
  CdtMetaData,
  CdtMetaOps,
  CdtMetaParam,
  Condition,
  ConditionItem,
  Role,
} from '@/types/role';
import { MinusOutlined } from '@ant-design/icons';
import {
  AutoComplete,
  Form,
  FormListFieldData,
  FormListOperation,
  Input,
  InputNumber,
  Select,
  Space,
} from 'antd';
import { FormInstance } from 'antd/lib';
import { useEffect, useRef, useState } from 'react';

interface Props {
  field: FormListFieldData;
  parentIndex: number;
  index: number;
  remove: (index: number | number[]) => void;
  cdtMetaData: CdtMetaData;
  form: FormInstance<Role>;
}

const booleOptions = [
  {
    label: '是',
    value: true,
  },
  {
    label: '否',
    value: false,
  },
];

const NewRoleFormItem = ({ field, parentIndex, index, form, remove, cdtMetaData }: Props) => {
  const [opsOptions, setOpsOptions] = useState<CdtMetaOps[]>([]);
  const [selectedParam, setSelectedParam] = useState<CdtMetaParam | undefined>(undefined);
  const [valueType, setValueType] = useState('string');
  const valueTypes = ['string', 'boolean', 'number'];
  const { isPc } = useWindowWidth();
  const handleSelect = (_, option) => {
    const selectedParam = cdtMetaData.params.find((param) => param.id === option.key);
    setSelectedParam(selectedParam);
    const newOps = cdtMetaData.ops.filter((op) => op.data_type == selectedParam?.data_type);

    if (selectedParam?.data_type == 'boolean') {
      selectedParam.values = ['是', '否'];
    }

    if (valueTypes.includes(selectedParam?.data_type ?? '')) {
      setValueType(selectedParam?.data_type ?? 'string');
    } else {
      setValueType('string');
    }

    setOpsOptions(newOps);
  };

  useEffect(() => {
    const statements = form.getFieldValue('statements');
    const condition = statements[parentIndex].condition[index];
    const selectedParam = cdtMetaData.params.find((param) => param.key === condition.param);
    handleSelect(null, {
      key: selectedParam?.id,
    });
    setValueType(selectedParam?.data_type ?? 'string');
  }, [cdtMetaData]);

  return (
    <Form.Item key={field.key} label={index === 0 ? '限制条件' : ''} required={false}>
      {!isPc && (
        <div className='w-full flex'>
          限制条件{index + 1}
          <div className='ml-auto'>
            <MinusOutlined className='ml-auto' onClick={() => remove(field.name)} />
          </div>
        </div>
      )}
      <Space key={field.key} align="baseline" direction={isPc ? 'horizontal' : 'vertical'}>
        <Form.Item
          noStyle
          name={[field.name, 'param']}
          rules={[{ required: true, message: '条件关键字' }]}
        >
          <Select
            className="role-form-select"
            bordered={false}
            style={{ width: 240 }}
            placeholder="条件关键字"
            options={cdtMetaData.params.map((item) => ({
              label: item.label ? (`${item.label}(${item.key})`) : item.key,
              value: item.key,
              key: item.id,
            }))}
            onSelect={handleSelect}
          />
        </Form.Item>
        <Form.Item
          noStyle
          name={[field.name, 'op']}
          rules={[{ required: true, message: '请选择限定词' }]}
        >
          <Select
            className="role-form-select"
            bordered={false}
            style={{ width: 200 }}
            placeholder="限定词"
            options={opsOptions.map((item) => ({
              label: item.desc,
              value: item.key,
            }))}
          />
        </Form.Item>
        <Form.Item
          noStyle
          name={[field.name, 'value']}
          rules={[{ required: true, message: '请输入值' }]}
        >
          {valueType == 'string' && (
            <AutoComplete
              className="role-form-input"
              bordered={false}
              options={selectedParam?.values.map((item) => ({
                value: item,
              }))}
              style={{ width: 120 }}
            />
          )}
          {valueType == 'boolean' && (
            <Select
              className="role-form-select"
              bordered={false}
              options={booleOptions}
              style={{ width: 120 }}
            />
          )}
          {valueType == 'number' && (
            <InputNumber className="role-form-input" bordered={false} style={{ width: 120 }} />
          )}
        </Form.Item>
        {isPc && <MinusOutlined onClick={() => remove(field.name)} />}
      </Space>
    </Form.Item>
  );
};

export default NewRoleFormItem;
